package com.zhuoli.service.springboot.mybatis.transaction.repository.service.impl;

import com.zhuoli.service.springboot.mybatis.transaction.common.enums.DataStatusEnum;
import com.zhuoli.service.springboot.mybatis.transaction.repository.aop.MultiTransactional;
import com.zhuoli.service.springboot.mybatis.transaction.repository.mapper.master.MasterUserMapper;
import com.zhuoli.service.springboot.mybatis.transaction.repository.mapper.slave.SlaveUserMapper;
import com.zhuoli.service.springboot.mybatis.transaction.repository.model.master.MasterUser;
import com.zhuoli.service.springboot.mybatis.transaction.repository.model.slave.SlaveUser;
import com.zhuoli.service.springboot.mybatis.transaction.repository.service.UserRepository;
import com.zhuoli.service.springboot.mybatis.transaction.repository.service.transaction.DbTxConstants;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Author: zhuoli
 * @Date: 2018/7/22 10:38
 * @Description:
 */
@Repository
@AllArgsConstructor
public class UserRepositoryImpl implements UserRepository {

    private MasterUserMapper masterUserMapper;

    private SlaveUserMapper slaveUserMapper;

    @Override
    @Transactional(value = "masterTransactionManager")
    public void createUser(String userName, String description) {
        MasterUser masterUser = new MasterUser();

        /*主数据库插入*/
        masterUser.setUserName(userName);
        masterUser.setDescription(description);
        masterUser.setIsDeleted(DataStatusEnum.EXIST.getCode());
        masterUserMapper.insertSelective(masterUser);

        /*从数据库插入*/
        SlaveUser slaveUser = new SlaveUser();
        slaveUser.setUserName(userName);
        slaveUser.setDescription(description);
        slaveUser.setIsDeleted(DataStatusEnum.EXIST.getCode());
        slaveUserMapper.insertSelective(slaveUser);
    }

    @Override
    @MultiTransactional(value = {DbTxConstants.DB1_TX, DbTxConstants.DB2_TX})
    public void createUserWithAnnotation(String userName, String description) {
        MasterUser masterUser = new MasterUser();

        /*主数据库插入*/
        masterUser.setUserName(userName);
        masterUser.setDescription(description);
        masterUser.setIsDeleted(DataStatusEnum.EXIST.getCode());
        masterUserMapper.insertSelective(masterUser);

        /*从数据库插入*/
        SlaveUser slaveUser = new SlaveUser();
        slaveUser.setUserName(userName);
        slaveUser.setDescription(description);
        slaveUser.setIsDeleted(DataStatusEnum.EXIST.getCode());
        slaveUserMapper.insertSelective(slaveUser);

        if (true){
            throw new RuntimeException("Exception");
        }
    }
}
